//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.visualdata.controller;

import ciicos.base.ActionResult;
import ciicos.base.NoDataSourceBind;
import ciicos.base.controller.SuperController;
import ciicos.base.vo.DownloadVO;
import ciicos.base.vo.ListVO;
import ciicos.config.ConfigValueUtil;
import ciicos.constant.MsgCode;
import ciicos.exception.DataException;
import ciicos.model.FileListVO;
import ciicos.util.FileUploadUtils;
import ciicos.util.FileUtil;
import ciicos.util.JsonUtil;
import ciicos.util.RandomUtil;
import ciicos.util.StringUtil;
import ciicos.util.UpUtil;
import ciicos.util.UserProvider;
import ciicos.util.VisusalImgUrl;
import ciicos.util.enums.ModuleTypeEnum;
import ciicos.util.file.FileExport;
import ciicos.visualdata.entity.VisualCategoryEntity;
import ciicos.visualdata.entity.VisualConfigEntity;
import ciicos.visualdata.entity.VisualEntity;
import ciicos.visualdata.enums.VisualImgEnum;
import ciicos.visualdata.model.VisualPageVO;
import ciicos.visualdata.model.visual.VisualApiRequest;
import ciicos.visualdata.model.visual.VisualCrform;
import ciicos.visualdata.model.visual.VisualInfoModel;
import ciicos.visualdata.model.visual.VisualInfoVO;
import ciicos.visualdata.model.visual.VisualListVO;
import ciicos.visualdata.model.visual.VisualModel;
import ciicos.visualdata.model.visual.VisualPaginationModel;
import ciicos.visualdata.model.visual.VisualProxyModel;
import ciicos.visualdata.model.visual.VisualSelectorVO;
import ciicos.visualdata.model.visual.VisualUpform;
import ciicos.visualdata.model.visualcategory.VisualCategoryListVO;
import ciicos.visualdata.model.visualconfig.VisualConfigInfoModel;
import ciicos.visualdata.model.visualfile.ImageVO;
import ciicos.visualdata.service.VisualCategoryService;
import ciicos.visualdata.service.VisualConfigService;
import ciicos.visualdata.service.VisualService;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.google.common.base.Joiner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javax.validation.Valid;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Tag(
        name = "大屏基本信息",
        description = "visual"
)
@RequestMapping({"/api/blade-visual/visual"})
public class VisualController extends SuperController<VisualService, VisualEntity> {
    @Autowired
    private FileExport fileExport;
    @Autowired
    private VisualService visualService;
    @Autowired
    private VisualConfigService configService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private VisualCategoryService categoryService;

    @Operation(
            summary = "分页"
    )
    @GetMapping({"/list"})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult<VisualPageVO<VisualListVO>> list(VisualPaginationModel pagination) {
        List<VisualEntity> data = this.visualService.getList(pagination);
        List<VisualListVO> list = JsonUtil.getJsonToList(data, VisualListVO.class);
        VisualPageVO paginationVO = (VisualPageVO)JsonUtil.getJsonToBean(pagination, VisualPageVO.class);
        paginationVO.setRecords(list);
        return ActionResult.success(paginationVO);
    }

    @Operation(
            summary = "详情"
    )
    @GetMapping({"/detail"})
    @Parameters({@Parameter(
            name = "id",
            description = "主键",
            required = true
    )})
    public ActionResult<VisualInfoVO> info(@RequestParam("id") String id) {
        VisualEntity visual = this.visualService.getInfo(id);
        VisualConfigEntity config = this.configService.getInfo(id);
        VisualInfoVO vo = new VisualInfoVO();
        vo.setVisual((VisualInfoModel)JsonUtil.getJsonToBean(visual, VisualInfoModel.class));
        vo.setConfig((VisualConfigInfoModel)JsonUtil.getJsonToBean(config, VisualConfigInfoModel.class));
        return ActionResult.success(vo);
    }

    @Operation(
            summary = "新增"
    )
    @PostMapping({"/save"})
    @Parameters({@Parameter(
            name = "visualCrform",
            description = "大屏模型",
            required = true
    )})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult create(@RequestBody @Valid VisualCrform visualCrform) {
        VisualEntity visual = (VisualEntity)JsonUtil.getJsonToBean(visualCrform.getVisual(), VisualEntity.class);
        visual.setBackgroundUrl(VisusalImgUrl.url + this.configValueUtil.getBiVisualPath() + "bg/bg1.png");
        VisualConfigEntity config = (VisualConfigEntity)JsonUtil.getJsonToBean(visualCrform.getConfig(), VisualConfigEntity.class);
        this.visualService.create(visual, config);
        Map<String, String> data = new HashMap(16);
        data.put("id", visual.getId());
        return ActionResult.success(data);
    }

    @Operation(
            summary = "修改"
    )
    @PostMapping({"/update"})
    @Parameters({@Parameter(
            name = "categoryUpForm",
            description = "大屏模型",
            required = true
    )})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult update(@RequestBody VisualUpform categoryUpForm) {
        VisualEntity visual = (VisualEntity)JsonUtil.getJsonToBean(categoryUpForm.getVisual(), VisualEntity.class);
        VisualConfigEntity config = (VisualConfigEntity)JsonUtil.getJsonToBean(categoryUpForm.getConfig(), VisualConfigEntity.class);
        this.visualService.update(visual.getId(), visual, config);
        return ActionResult.success("更新成功");
    }

    @Operation(
            summary = "删除"
    )
    @PostMapping({"/remove"})
    @Parameters({@Parameter(
            name = "ids",
            description = "主键",
            required = true
    )})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult delete(@RequestParam("ids") String ids) {
        VisualEntity entity = this.visualService.getInfo(ids);
        if (entity != null) {
            this.visualService.delete(entity);
            return ActionResult.success("删除成功");
        } else {
            return ActionResult.fail("删除失败，数据不存在");
        }
    }

    @Operation(
            summary = "复制"
    )
    @PostMapping({"/copy"})
    @Parameters({@Parameter(
            name = "id",
            description = "主键",
            required = true
    )})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult copy(@RequestParam("id") String id) {
        VisualEntity entity = this.visualService.getInfo(id);
        VisualConfigEntity config = this.configService.getInfo(id);
        if (entity != null) {
            entity.setTitle(entity.getTitle() + "_复制");
            this.visualService.create(entity, config);
            return ActionResult.success("操作成功", entity.getId());
        } else {
            return ActionResult.fail("复制失败");
        }
    }

    @Operation(
            summary = "获取类型"
    )
    @GetMapping({"/category"})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult<List<VisualCategoryListVO>> list() {
        List<VisualCategoryEntity> data = this.categoryService.getList();
        List<VisualCategoryListVO> list = JsonUtil.getJsonToList(data, VisualCategoryListVO.class);
        return ActionResult.success(list);
    }

    @NoDataSourceBind
    @Operation(
            summary = "上传文件"
    )
    @Parameters({@Parameter(
            name = "type",
            description = "类型",
            required = true
    )})
    @PostMapping(
            value = {"/put-file/{type}"},
            consumes = {"multipart/form-data"}
    )
    public ActionResult<ImageVO> file(MultipartFile file, @PathVariable("type") String type) {
        ImageVO vo = new ImageVO();
        VisualImgEnum imgEnum = VisualImgEnum.getByMessage(type);
        if (imgEnum != null) {
            String path = imgEnum.getMessage();
            String filePath = this.configValueUtil.getBiVisualPath() + path + "/";
            String name = RandomUtil.uuId() + "." + UpUtil.getFileType(file);
            FileInfo fileInfo = FileUploadUtils.uploadFile(file, filePath, name);
            vo.setOriginalName(fileInfo.getOriginalFilename());
            vo.setLink(VisusalImgUrl.url + fileInfo.getPath() + fileInfo.getFilename());
            vo.setName(VisusalImgUrl.url + fileInfo.getPath() + fileInfo.getFilename());
        }

        return ActionResult.success(vo);
    }

    @NoDataSourceBind
    @Operation(
            summary = "获取图片列表"
    )
    @GetMapping({"/{type}"})
    @Parameters({@Parameter(
            name = "type",
            description = "文件夹",
            required = true
    )})
    public ActionResult<List<ImageVO>> getFile(@PathVariable("type") String type) {
        List<ImageVO> vo = new ArrayList();
        VisualImgEnum imgEnum = VisualImgEnum.getByMessage(type);
        if (imgEnum != null) {
            String path = this.configValueUtil.getBiVisualPath() + imgEnum.getMessage() + "/";
            List<FileListVO> fileList = FileUploadUtils.getFileList(path);
            fileList.forEach((fileListVO) -> {
                ImageVO imageVO = new ImageVO();
                imageVO.setName(fileListVO.getFileName());
                imageVO.setLink(VisusalImgUrl.url + fileListVO.getFileName());
                imageVO.setOriginalName(fileListVO.getFileName());
                vo.add(imageVO);
            });
        }

        return ActionResult.success(vo);
    }

    @Operation(
            summary = "大屏下拉框"
    )
    @GetMapping({"/Selector"})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult<ListVO<VisualSelectorVO>> selector() {
        List<VisualEntity> visualList = this.visualService.getList();
        List<VisualCategoryEntity> categoryList = this.categoryService.getList();
        List<VisualSelectorVO> listVos = new ArrayList();

        for(VisualCategoryEntity category : categoryList) {
            VisualSelectorVO categoryModel = new VisualSelectorVO();
            categoryModel.setId(category.getCategoryvalue());
            categoryModel.setFullName(category.getCategorykey());
            List<VisualEntity> visualAll = (List)visualList.stream().filter((t) -> t.getCategory().equals(category.getCategoryvalue())).collect(Collectors.toList());
            if (visualAll.size() > 0) {
                List<VisualSelectorVO> childList = new ArrayList();

                for(VisualEntity visual : visualAll) {
                    VisualSelectorVO visualModel = new VisualSelectorVO();
                    visualModel.setId(visual.getId());
                    visualModel.setFullName(visual.getTitle());
                    visualModel.setChildren((List)null);
                    visualModel.setHasChildren(false);
                    childList.add(visualModel);
                }

                categoryModel.setHasChildren(true);
                categoryModel.setChildren(childList);
                listVos.add(categoryModel);
            }
        }

        ListVO vo = new ListVO();
        vo.setList(listVos);
        return ActionResult.success(vo);
    }

    @Operation(
            summary = "大屏导出"
    )
    @PostMapping({"/{id}/Actions/ExportData"})
    @Parameters({@Parameter(
            name = "id",
            description = "主键",
            required = true
    )})
    @SaCheckPermission({"onlineDev.dataScreen"})
    public ActionResult<DownloadVO> exportData(@PathVariable("id") String id) {
        VisualEntity entity = this.visualService.getInfo(id);
        VisualConfigEntity configEntity = this.configService.getInfo(id);
        VisualModel model = new VisualModel();
        model.setEntity(entity);
        model.setConfigEntity(configEntity);
        DownloadVO downloadVO = this.fileExport.exportFile(model, this.configValueUtil.getTemporaryFilePath(), entity.getTitle(), ModuleTypeEnum.VISUAL_DATA.getTableName());
        return ActionResult.success(downloadVO);
    }

    @Operation(
            summary = "大屏导入"
    )
    @SaCheckPermission({"onlineDev.dataScreen"})
    @PostMapping(
            value = {"/Model/Actions/ImportData"},
            consumes = {"multipart/form-data"}
    )
    public ActionResult ImportData(MultipartFile multipartFile) throws DataException {
        if (FileUtil.existsSuffix(multipartFile, ModuleTypeEnum.VISUAL_DATA.getTableName())) {
            return ActionResult.fail(MsgCode.IMP002.get());
        } else {
            String fileContent = FileUtil.getFileContent(multipartFile);
            VisualModel vo = (VisualModel)JsonUtil.getJsonToBean(fileContent, VisualModel.class);
            this.visualService.createImport(vo.getEntity(), vo.getConfigEntity());
            return ActionResult.success(MsgCode.SU000.get());
        }
    }

    @Operation(
            summary = "获取API动态数据"
    )
    @PostMapping({"/GetApiData"})
    @Parameters({@Parameter(
            name = "apiRequest",
            description = "大屏模型",
            required = true
    )})
    public String getApiData(@RequestBody @Valid VisualApiRequest apiRequest) throws IOException {
        OkHttpClient client = (new OkHttpClient.Builder()).callTimeout(Duration.ofSeconds((long)apiRequest.getTimeout())).build();
        Headers headers;
        if (!apiRequest.getHeaders().isEmpty()) {
            Headers.Builder builder = new Headers.Builder();
            apiRequest.getHeaders().forEach((k, v) -> builder.add(k, v));
            headers = builder.build();
        } else {
            headers = (new Headers.Builder()).build();
        }

        Request request;
        if (apiRequest.getMethod().equalsIgnoreCase("post")) {
            request = (new Request.Builder()).url(apiRequest.getUrl()).post(okhttp3.RequestBody.create(MediaType.parse("application/json;charset=utf-8"), apiRequest.getParams().isEmpty() ? "" : JsonUtil.getObjectToString(apiRequest.getParams()))).headers(headers).build();
        } else {
            String params = Joiner.on("&").useForNull("").withKeyValueSeparator("=").join(apiRequest.getParams());
            request = (new Request.Builder()).url(apiRequest.getUrl() + (apiRequest.getUrl().contains("?") ? "&" : "?") + params).get().headers(headers).build();
        }

        return client.newCall(request).execute().body().string();
    }

    @Operation(
            summary = "获取API动态数据"
    )
    @PostMapping({"/proxy"})
    @Parameters({@Parameter(
            name = "proxyModel",
            description = "代理模型",
            required = true
    )})
    public String getApiData(@RequestBody @Valid VisualProxyModel proxyModel) throws IOException {
        boolean isForm = false;
        Map<String, String> headers;
        if (!proxyModel.getHeaders().isEmpty()) {
            headers = new TreeMap(String.CASE_INSENSITIVE_ORDER);
            headers.putAll(proxyModel.getHeaders());
            if (headers.containsKey("form")) {
                isForm = true;
            }
        } else {
            headers = new HashMap(1, 1.0F);
        }

        if (!headers.containsKey("Authorization")) {
            String token = UserProvider.getToken();
            if (StringUtil.isNotEmpty(token)) {
                headers.put("Authorization", token);
            }
        }

        HttpRequest httpRequest = (HttpRequest)HttpRequest.of(proxyModel.getUrl()).method(Method.valueOf(proxyModel.getMethod().toUpperCase())).addHeaders(headers);
        if (isForm) {
            httpRequest.form(proxyModel.getData());
        } else if (proxyModel.getData() != null && !proxyModel.getData().isEmpty()) {
            httpRequest.body(JsonUtil.getObjectToString(proxyModel.getData()));
        } else {
            httpRequest.form(proxyModel.getParams());
        }

        return httpRequest.timeout(10000).execute().body();
    }
}
